﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Xml.Linq;
using WpfApp1.bean;
using WpfApp1.Contacts;
using WpfApp1.Httpwork;
using WpfApp1.Unit;

namespace WpfApp1
{
    /// <summary>
    /// Window3.xaml 的交互逻辑
    /// </summary>
    public partial class Setting : Window
    {

        ArrayList panchuankous;
        //List<String> category;

        String[] chuankous;
        //ArrayList yixuan_chuankous = new ArrayList();
        //MainWindowViewModel categoryModel;
        string sao_portName = "";
        string deng_portName = "";

        string sao_baudRate = "";
        string deng_baudRate = "";

        string sao_parity = "";
        string deng_parity = "";

        string sao_dataBits = "";
        string deng_dataBits = "";

        string sao_stopBits = "";
        string deng_stopBits = "";

        string buffers = "";
        string AP = "";

        string rate = "";
        public Setting(ArrayList panchuankous)
        {
            //this.category = category;
            this.panchuankous = panchuankous;
            InitializeComponent();
            chuankous = SerialPort.GetPortNames();
            if (chuankous.Length > 0)
            {
                for (int i = 0; i < chuankous.Length; i++)
                {
                    Console.WriteLine(chuankous[i]);

                }
                com_sao_portName.ItemsSource = chuankous;
                com_deng_portName.ItemsSource = chuankous;
            }
            else
            {
                Console.WriteLine("没找到");
            }
            //String c = HttpMaterial_category();

            String[] baudRates = { "300", "600", "1200", "2400", "4800", "9600", "19200", "38400", "43000", "56000", "576000", "115200" };
            String[] paritys = { "NONE", "ODD", "EVEN" };
            String[] dataBitss = {"6", "7", "8"};
            String[] stopBitss = { "None", "ONE", "TWO" };
            com_sao_baudRate.ItemsSource = baudRates;
            com_deng_baudRate.ItemsSource = baudRates;

            com_sao_parity.ItemsSource = paritys;
            com_deng_parity.ItemsSource = paritys;

            com_sao_dataBits.ItemsSource = dataBitss;
            com_deng_dataBits.ItemsSource = dataBitss;

            com_sao_stopBits.ItemsSource = stopBitss;
            com_deng_stopBits.ItemsSource = stopBitss;

            readcmom();
            com_sao_portName.Text = sao_portName;
            com_deng_portName.Text = deng_portName;

            com_sao_baudRate.Text = sao_baudRate;
            com_deng_baudRate.Text = deng_baudRate;

            com_sao_parity.Text = sao_parity;
            com_deng_parity.Text = deng_parity;

            com_sao_dataBits.Text = sao_dataBits;
            com_deng_dataBits.Text = deng_dataBits;

            com_sao_stopBits.Text = sao_stopBits;
            com_deng_stopBits.Text = deng_stopBits;

            readbuffer();
            buffers_TB.Text = buffers;
            buffers_AP.Text = AP;

            Rate.Text = rate;
        }

        public void readcmom()
        {
            string filePath = MainWindow.path + "save\\com_setting.xml";
            if (File.Exists(filePath))
            {
                XElement xmlDoc = XElement.Load(filePath);
                sao_portName = xmlDoc.Attribute("sao_portName").Value;
                deng_portName = xmlDoc.Attribute("deng_portName").Value;

                sao_baudRate = xmlDoc.Attribute("sao_baudRate").Value;
                deng_baudRate = xmlDoc.Attribute("deng_baudRate").Value;

                sao_parity = xmlDoc.Attribute("sao_parity").Value;
                deng_parity = xmlDoc.Attribute("deng_parity").Value;

                sao_dataBits = xmlDoc.Attribute("sao_dataBits").Value;
                deng_dataBits = xmlDoc.Attribute("deng_dataBits").Value;

                sao_stopBits = xmlDoc.Attribute("sao_stopBits").Value;
                deng_stopBits = xmlDoc.Attribute("deng_stopBits").Value;

            }

        }

        public void readbuffer()
        {
            string filePath = MainWindow.path + "save\\buffer_setting.xml";
            if (File.Exists(filePath))
            {
                XElement xmlDoc = XElement.Load(filePath);
                buffers = xmlDoc.Attribute("buffer_postions").Value;
            }

            string filePathap = MainWindow.path + "save\\ap_setting.xml";
            if (File.Exists(filePathap))
            {
                XElement xmlDoc = XElement.Load(filePathap);
                AP = xmlDoc.Attribute("bufferap").Value;
            }

            string filePathrate = MainWindow.path + "save\\rate_setting.xml";
            if (File.Exists(filePathrate))
            {
                XElement xmlDoc = XElement.Load(filePathrate);
                rate = xmlDoc.Attribute("ratey").Value;
            }
        }

        /**写入串口设置*/
        public void writCom()
        {
            string filePath = MainWindow.path + "save\\com_setting.xml";
            if (!File.Exists(filePath))
            {
                FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                fs.Close();
            }
            XElement XEbean = new XElement("COM",
                                new XAttribute("sao_portName", com_sao_portName.Text),
                                new XAttribute("deng_portName", com_deng_portName.Text),
                                new XAttribute("sao_baudRate", com_sao_baudRate.Text),
                                new XAttribute("deng_baudRate", com_deng_baudRate.Text),
                                new XAttribute("sao_parity", com_sao_parity.Text),
                                new XAttribute("deng_parity", com_deng_parity.Text),
                                new XAttribute("sao_dataBits", com_sao_dataBits.Text),
                                new XAttribute("deng_dataBits", com_deng_dataBits.Text),
                                new XAttribute("sao_stopBits", com_sao_stopBits.Text),
                                new XAttribute("deng_stopBits", com_deng_stopBits.Text));
            XEbean.Save(filePath);
        }

        /**写入缓冲仓位设置*/
        public void writBuffers()
        {
            string filePath = MainWindow.path + "save\\buffer_setting.xml";
            if (!File.Exists(filePath))
            {
                FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                fs.Close();
            }
            XElement XEbean = new XElement("buffer",
                                new XAttribute("buffer_postions", buffers_TB.Text));
            XEbean.Save(filePath);

            if (!buffers_TB.Text.Contains(buffers_AP.Text))
            {
                MessageBox.Show("设置的AP托盘缓冲位置必须在位置列表中");
                return;
            }

            string filePathap = MainWindow.path + "save\\ap_setting.xml";
            if (!File.Exists(filePathap))
            {
                FileStream fs = new FileStream(filePathap, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                fs.Close();
            }
            XElement XEbeanap = new XElement("buffer",
                                new XAttribute("bufferap", buffers_AP.Text));
            XEbeanap.Save(filePathap);

            string filePathrate = MainWindow.path + "save\\rate_setting.xml";
            if (!File.Exists(filePathrate))
            {
                FileStream fs = new FileStream(filePathrate, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                fs.Close();
            }
            XElement XEbeanrate = new XElement("rate",
                                new XAttribute("ratey", Rate.Text));
            XEbeanrate.Save(filePathrate);
        }

        private void CB_Genggai_DropDownClosed(object sender, EventArgs e)
        {
            //cleanchuakou();
        }

        public delegate void GetTextHandler(); //声明委托
        public GetTextHandler getTextHandler;                //委托对象

        private void OnButtonClick_queding(object sender, RoutedEventArgs e)
        {
            //writcategory();
            writCom();
            writBuffers();
            getTextHandler();
            Window window = Window.GetWindow(this);//关闭父窗体
            window.Close();
        }

        private void OnButtonClick_quxiao(object sender, RoutedEventArgs e)
        {
            Window window = Window.GetWindow(this);//关闭父窗体
            window.Close();
        }

        //private String HttpMaterial_category()
        //{
        //    string url = contacts.MATERIAL_CATEGORY;
        //    //string url = MainWindow.http + "?q=app/material_quality/configuration/material_category";
        //    Boolean b = true;
        //    string result = "";
        //    HttpWebRequest req = Http.getHttp(url);
        //    HttpWebResponse resp;
        //    try
        //    {
        //        resp = (HttpWebResponse)req.GetResponse();
        //        b = true;
        //    }
        //    catch (WebException ex)
        //    {
        //        resp = (HttpWebResponse)ex.Response;
        //        b = false;
        //    }
        //    Stream stream = resp.GetResponseStream();
        //    //获取响应内容
        //    using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
        //    {
        //        result = reader.ReadToEnd();
        //    }
        //    Console.WriteLine(result);
        //    Json(result);
        //    return result;
        //}

        //private void Json(String data)
        //{
        //    JObject obj = JObject.Parse(data);

        //    Console.WriteLine(obj.Count);
        //    List<Book> beans = new List<Book>();
        //    foreach (var x in obj)
        //    {
        //        Book bean = new Book() { key = x.Key, Name = (String)x.Value };
        //        beans.Add(bean);
        //    }

        //    categoryModel = new MainWindowViewModel(beans,category);
        //    this.DataContext = categoryModel;
        //}
    }

    //public class MainWindowViewModel : ObservableObject
    //{
    //    private string _selectedText = string.Empty;

    //    public string SelectedText
    //    {
    //        get
    //        {
    //            return _selectedText;
    //        }
    //        set
    //        {
    //            if (_selectedText != value)
    //            {
    //                _selectedText = value;

    //                RaisePropertyChanged("SelectedText");
    //            }
    //        }
    //    }

    //    private ObservableCollection<BookEx> _books;

    //    public ObservableCollection<BookEx> BookExs
    //    {
    //        get
    //        {
    //            if (_books == null)
    //            {
    //                _books = new ObservableCollection<BookEx>();

    //                _books.CollectionChanged += (sender, e) =>
    //                {
    //                    if (e.OldItems != null)
    //                    {
    //                        foreach (BookEx bookEx in e.OldItems)
    //                        {
    //                            bookEx.PropertyChanged -= ItemPropertyChanged;
    //                        }
    //                    }

    //                    if (e.NewItems != null)
    //                    {
    //                        foreach (BookEx bookEx in e.NewItems)
    //                        {
    //                            bookEx.PropertyChanged += ItemPropertyChanged;
    //                        }
    //                    }
    //                };
    //            }

    //            return _books;
    //        }
    //    }

    //    private void ItemPropertyChanged(object sender, PropertyChangedEventArgs e)
    //    {
    //        if (e.PropertyName == "IsChecked")
    //        {
    //            BookEx bookEx = sender as BookEx;

    //            if (bookEx != null)
    //            {
    //                IEnumerable<BookEx> bookExs = BookExs.Where(b => b.IsChecked == true);
                   
    //                StringBuilder builder = new StringBuilder();

    //                foreach (BookEx item in bookExs)
    //                {
    //                    builder.Append(item.Book.Name + " ");
    //                }

    //                SelectedText = builder == null ? string.Empty : builder.ToString();
    //            }
    //        }
    //    }

    //    public MainWindowViewModel(List<Book> beans,List<String> category)
    //    {
    //        StringBuilder builder = new StringBuilder();
    //        foreach (Book bean in beans)
    //        {
    //            BookEx b = new BookEx(bean);
    //            if (category.Contains(bean.key))
    //            {
    //                b.IsChecked = true;
    //                builder.Append(bean.Name + " ");
    //            }
    //            BookExs.Add(b);

    //            SelectedText = builder == null ? string.Empty : builder.ToString();
    //        }
            
    //    }
    //}

    //public class Book
    //{
    //    public string key { get; set; }
    //    public string Name { get; set; }
    //}

    //public class BookEx : ObservableObject
    //{
    //    public Book Book { get; private set; }

    //    private bool _isChecked;

    //    public bool IsChecked
    //    {
    //        get
    //        {
    //            return _isChecked;
    //        }
    //        set
    //        {
    //            if (_isChecked != value)
    //            {
    //                _isChecked = value;

    //                RaisePropertyChanged("IsChecked");
    //            }
    //        }
    //    }

    //    public BookEx(Book book)
    //    {
    //        Book = book;
    //    }
    //}

    //public class ObservableObject : INotifyPropertyChanged
    //{
    //    public event PropertyChangedEventHandler PropertyChanged;

    //    protected void RaisePropertyChanged(string propertyName)
    //    {
    //        if (PropertyChanged != null)
    //        {
    //            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    //        }
    //    }
    //}
}
